package com.ywjh.inter.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ywjh.inter.entity.BGluRangeEntity;
import com.ywjh.inter.entity.BloodGlucoseEntity;
import com.ywjh.inter.entity.UsersEntity;
import com.ywjh.inter.service.PatientDataService;
import com.ywjh.inter.service.SettingService;
import com.ywjh.inter.service.UsersService;
import com.ywjh.inter.utils.StrUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class BloodGlucose extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -1737303311126608455L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html; charset=utf-8");
		int r = 0;
		String e = "";

		JSONObject postData = StrUtil.getPostJSON(req);
		String act = postData.getString("act");
		JSONObject data = postData.getJSONObject("data");
		JSONObject json = new JSONObject();
		System.out.println("blood_glu="+postData.toString());
		switch (act) {
		case "import":
			String phone = data.getString("phone");
			UsersEntity users=UsersService.getInstance().findUserByPhone(phone);
			float glu = StrUtil.getFloat(data.getString("data"), 0.0f);
			Timestamp time = StrUtil.getTimestampHHMISS(data.getString("time"));
			String memo = data.getString("memo");
			int planId= UsersService.getInstance().getCurrentBgluPlanId(time,users.getId());
			BloodGlucoseEntity bg = new BloodGlucoseEntity();
			bg.setCheck_time(time);
			bg.setAdd_time(new Timestamp(System.currentTimeMillis()));
			bg.setData(glu);
			bg.setStatus(1);
			bg.setUser_id(users.getId());
			bg.setPlan_id(planId);
			bg.setMemo(memo);
			bg.setData_source("APP");
			boolean b = PatientDataService.getInstance().addBloodGlucose(bg);
			if (b) {
				r = 1;
			} else {
				e = "数据库错误";
			}
			break;
		case "add":
			 int userId = data.getInt("user_id");
			 glu = StrUtil.getFloat(data.getString("data"), 0.0f);
			 time = StrUtil.getTimestampHHMISS(data.getString("time"));
			 memo = data.getString("memo");
			 planId = data.getInt("plan_id");
			 bg = new BloodGlucoseEntity();
			bg.setCheck_time(time);
			bg.setAdd_time(new Timestamp(System.currentTimeMillis()));
			bg.setData(glu);
			bg.setStatus(1);
			bg.setUser_id(userId);
			bg.setPlan_id(planId);
			bg.setMemo(memo);
			bg.setData_source("APP");
			 b = PatientDataService.getInstance().addBloodGlucose(bg);
			if (b) {
				r = 1;
			} else {
				e = "数据库错误";
			}
			break;

		case "update":
			int id = data.getInt("id");
			userId = data.getInt("user_id");
			memo = data.getString("memo");
			glu = StrUtil.getFloat(data.getString("data"), 0.0f);
			time = StrUtil.getTimestampHHMISS(data.getString("time"));
			planId = data.getInt("plan_id");
			bg = PatientDataService.getInstance().findBloodGlucoseById(id);
			bg.setCheck_time(time);
			bg.setAdd_time(new Timestamp(System.currentTimeMillis()));
			bg.setData(glu);
			bg.setStatus(1);
			bg.setPlan_id(planId);
			bg.setUser_id(userId);
			bg.setMemo(memo);
			bg.setData_source("APP");
			b = PatientDataService.getInstance().updateBloodGlucose(bg);
			if (b) {
				r = 1;
			} else {
				e = "数据库错误";
			}
			break;
		case "find":
			id = data.getInt("id");
			bg = PatientDataService.getInstance().findBloodGlucoseById(id);
			JSONObject d = new JSONObject();
			if (bg != null) {
				d.put("id", bg.getId());
				d.put("data", bg.getData());
				d.put("user_id", bg.getUser_id());
				d.put("check_time", StrUtil.getYYYYMMDDHHMISS(bg.getCheck_time()));
				d.put("add_time", StrUtil.getYYYYMMDDHHMISS(bg.getAdd_time()));
				d.put("plan_id", bg.getPlan_id());
				d.put("memo", bg.getMemo());
				d.put("data_source", bg.getData_source());
			}
			r = 1;
			json.put("d", d);
			break;
		case "data":
			userId = data.getInt("user_id");
			String startTime = data.getString("start_time");
			String endTime = data.getString("end_time");
			d = new JSONObject();

			Map<String, Map<Integer, List<BloodGlucoseEntity>>> bGluMap = PatientDataService.getInstance()
					.findBloodGlucoseByTime(startTime, endTime, userId);
			Map<Integer, BGluRangeEntity> userBgluAlertMap = SettingService.getInstance().getBgluRange(userId);
			for (String dataTime : bGluMap.keySet()) {
				Map<Integer, List<BloodGlucoseEntity>> planDataMap = bGluMap.get(dataTime);
				JSONObject planDataJson = new JSONObject();
				for (int plan_id : planDataMap.keySet()) {
					List<BloodGlucoseEntity> dataList = planDataMap.get(plan_id);
					BGluRangeEntity gluRangeEntity = userBgluAlertMap.get(plan_id);
					float low = 0.0f;
					float hi = 0.0f;
					if (gluRangeEntity != null) {
						String[] alert = gluRangeEntity.getWarning_range().split(";");
						low = Float.parseFloat(alert[0]);
						hi = Float.parseFloat(alert[1]);
					}
					JSONArray timeDataArray = new JSONArray();
					for (BloodGlucoseEntity entity : dataList) {
						JSONObject bgluJson = new JSONObject();
						bgluJson.put("id", entity.getId());
						bgluJson.put("data", entity.getData());
						bgluJson.put("check_time", StrUtil.getYYYYMMDDHHMISS(entity.getCheck_time()));
						bgluJson.put("memo", entity.getMemo());
						bgluJson.put("data_source", entity.getData_source());
						if (entity.getData() <= low && low > 0) {
							bgluJson.put("is_warning", 1);// 红色
						} else if (entity.getData() >= hi && hi > 0) {
							bgluJson.put("is_warning", 2);// 橙色
						} else {
							bgluJson.put("is_warning", 0);// 绿色
						}
						timeDataArray.add(bgluJson);
					}
					planDataJson.put(plan_id, timeDataArray);
				}
				d.put(dataTime, planDataJson);
			}
			r = 1;
			json.put("d", d);
			break;
		case "overview":
			userId = data.getInt("user_id");
			startTime = data.getString("start_time");
			endTime = data.getString("end_time");
			userBgluAlertMap = SettingService.getInstance().getBgluRange(userId);
			List<BloodGlucoseEntity> list = PatientDataService.getInstance().listBloodGlucoseByTime(startTime, endTime,
					userId);
			int total = list.size();
			int total_ok = 0;
			int total_low = 0;
			int total_hi = 0;
			float total_sum = 0;

			int before_total = 0;
			int before_ok = 0;
			int before_low = 0;
			int before_hi = 0;
			float before_sum = 0;

			int after_total = 0;
			int after_ok = 0;
			int after_low = 0;
			int after_hi = 0;
			float after_sum = 0;

			int sleep_total = 0;
			int sleep_ok = 0;
			int sleep_low = 0;
			int sleep_hi = 0;
			float sleep_sum = 0;

			float highest = 0;
			float lowest = 0;

			int total3 = 0;
			float sum_total3 = 0;
			int total5 = 0;
			float sum_total5 = 0;
			int total7 = 0;
			float sum_total7 = 0;

			int total2 = 0;
			float sum_total2 = 0;
			int total4 = 0;
			float sum_total4 = 0;
			int total6 = 0;
			float sum_total6 = 0;

			for (BloodGlucoseEntity bgEntity : list) {
				total_sum += bgEntity.getData();
				BGluRangeEntity gluRangeEntity = userBgluAlertMap.get(bgEntity.getPlan_id());
				float low = 0.0f;
				float hi = 0.0f;
				if (gluRangeEntity != null) {
					String[] alert = gluRangeEntity.getWarning_range().split(";");
					low = Float.parseFloat(alert[0]);
					hi = Float.parseFloat(alert[1]);
				}
				if (bgEntity.getData() > highest) {
					highest = bgEntity.getData();
				}
				if (bgEntity.getData() < lowest||lowest==0) {
					lowest = bgEntity.getData();
				}

				if (bgEntity.getData() <= low && low > 0) {
					total_low++;
				} else if (bgEntity.getData() >= hi && hi > 0) {
					total_hi++;
				} else {
					total_ok++;
				}
				if (bgEntity.getPlan_id() == 2 || bgEntity.getPlan_id() == 4 || bgEntity.getPlan_id() == 6) {
					before_sum += bgEntity.getData();
					before_total++;
					if (bgEntity.getData() <= low && low > 0) {
						before_low++;
					} else if (bgEntity.getData() >= hi && hi > 0) {
						before_hi++;
					} else {
						before_ok++;
					}
				}
				if (bgEntity.getPlan_id() == 3 || bgEntity.getPlan_id() == 5 || bgEntity.getPlan_id() == 7) {
					after_sum += bgEntity.getData();
					after_total++;
					if (bgEntity.getData() <= low && low > 0) {
						after_low++;
					} else if (bgEntity.getData() >= hi && hi > 0) {
						after_hi++;
					} else {
						after_ok++;
					}
				}
				if (bgEntity.getPlan_id() == 8) {
					sleep_sum += bgEntity.getData();
					sleep_total++;
					if (bgEntity.getData() <= low && low > 0) {
						sleep_low++;
					} else if (bgEntity.getData() >= hi && hi > 0) {
						sleep_hi++;
					} else {
						sleep_ok++;
					}
				}

				if (bgEntity.getPlan_id() == 3) {
					sum_total3 += bgEntity.getData();
					total3++;
				}
				if (bgEntity.getPlan_id() == 5) {
					sum_total5 += bgEntity.getData();
					total5++;
				}
				if (bgEntity.getPlan_id() == 7) {
					sum_total7 += bgEntity.getData();
					total7++;
				}
				if (bgEntity.getPlan_id() == 2) {
					sum_total2 += bgEntity.getData();
					total2++;
				}
				if (bgEntity.getPlan_id() == 4) {
					sum_total4 += bgEntity.getData();
					total4++;
				}
				if (bgEntity.getPlan_id() == 6) {
					sum_total6 += bgEntity.getData();
					total6++;
				}

			}
			JSONObject over = new JSONObject();
			over.put("total", total);
			over.put("total_ok", total_ok);
			over.put("total_hi", total_hi);
			over.put("total_low", total_low);
			over.put("total_avg", total_sum == 0 ? 0 : StrUtil.round(total_sum / total, 2));

			over.put("before_total", before_total);
			over.put("before_ok", before_ok);
			over.put("before_hi", before_hi);
			over.put("before_low", before_low);
			over.put("before_avg", before_sum == 0 ? 0 : StrUtil.round(before_sum / before_total, 2));

			over.put("after_total", after_total);
			over.put("after_ok", after_ok);
			over.put("after_hi", after_hi);
			over.put("after_low", after_low);
			over.put("after_avg", after_sum == 0 ? 0 : StrUtil.round(after_sum / after_total, 2));

			over.put("sleep_total", sleep_total);
			over.put("sleep_ok", sleep_ok);
			over.put("sleep_hi", sleep_hi);
			over.put("sleep_low", sleep_low);
			over.put("sleep_avg", sleep_sum == 0 ? 0 : StrUtil.round(sleep_sum / after_total, 2));

			over.put("highest", highest);
			over.put("lowest", lowest);
			over.put("before_bf_avg", sum_total2 == 0 ? 0 : StrUtil.round(sum_total2 / total2, 2));
			over.put("after_bf_avg", sum_total3 == 0 ? 0 : StrUtil.round(sum_total3 / total3, 2));
			over.put("before_lc_avg", sum_total4 == 0 ? 0 : StrUtil.round(sum_total4 / total4, 2));
			over.put("after_lc_avg", sum_total5 == 0 ? 0 : StrUtil.round(sum_total5 / total5, 2));
			over.put("before_dn_avg", sum_total6 == 0 ? 0 : StrUtil.round(sum_total6 / total6, 2));
			over.put("after_dn_avg", sum_total7 == 0 ? 0 : StrUtil.round(sum_total7 / total7, 2));
			json.put("d", over);
			r = 1;
		}

		json.put("r", r);
		json.put("e", e);
		PrintWriter pw = resp.getWriter();
		pw.write(json.toString());
		pw.flush();
		pw.close();
	}
}
